<!--
 * @Descripttion: 
 * @version: 
 * @Author: sueRimn
 * @Date: 2020-06-20 09:37:34
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-06-24 08:52:53
--> 
<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button
      type="success"
      v-if="isedit"
      @click="batchSave"
      size="mini"
      icon="el-icon-check"
      circle
    ></el-button>
    <el-button type="danger" @click="batchDelete" size="mini" icon="el-icon-delete" circle></el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span class="">
          <el-button v-if="node.level<=2" type="success"  size="mini" @click="() => append(data)">add</el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="() => edit(data)"></el-button>

          <el-button
            v-if="node.childNodes.length==0"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="() => remove(node, data)"
          ></el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUunit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      draggable: false,
      isedit: false,
      pCid: [],
      title: "",
      menus: [],
      updateNodes: [],
      expandedKey: [],
      dialogVisible: false,
      dialogType: "",
      maxLevel: 0,
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUunit: ""
      },
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  methods: {
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/updates"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "分类集体修改成功!"
        });
        // 刷新菜单
        this.getMenus();
        // 默认展开菜单
        this.expandedKey = this.pCid;
        this.updateNodes = [];
        this.maxLevel = 0;
        this.isedit = false;
      });
    },
    batchDelete() {
      let nodes = this.$refs.tree.getCheckedNodes();
      let names = [];
      if (nodes != null && nodes.length > 0) {
        for (let i = 0; i < nodes.length; i++) {
          names.push(nodes[i].name);
        }
        let ids = this.$refs.tree.getCheckedKeys();
        this.categoryDelete(ids, names);
        names = [];
      }else{
        this.$message.error('请选中要删除的菜单！');
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      console.log(
        "allowDrop -> draggingNode, dropNode, type",
        draggingNode,
        dropNode,
        type
      );
      this.countNodeLevel(draggingNode.data);
      if (type == "inner") {
        return this.maxLevel + dropNode.level <= 3;
      } else {
        return this.maxLevel + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      console.log("countNodeLevel -> node", node);
      // 找到所有子节点，求出最大深度
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            this.maxLevel = node.children[i].catLevel;
            console.log("countNodeLevel -> this.maxLevel", this.maxLevel);
          }
          this.countNodeLevel(node.children[i]);
        }
      }
    },
    // 节点拖动后事件
    handleDrop(draggingNode, dropNode, dropType, ev) {
      this.isedit = true;
      let pCid = 0;
      let siblings = [];
      if (dropType != "inner") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);

      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          let catLevel = draggingNode.level;
          if (catLevel != siblings[i].level) {
            catLevel = siblings[i].level;
            this.updateChildrenNodes(siblings[i]);
          }

          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      console.log("handleDrop -> updateNodes", this.updateNodes);
    },
    updateChildrenNodes(node) {
      if (node.childrens.length > 0) {
        for (let i = 0; i < node.childrens.length; i++) {
          var cNode = node.childrens[i];
          this.updateNodes.push({
            catId: cNode.data.catId,
            catLevel: cNode.level
          });
          this.updateChildrenNodes(cNode);
        }
      }
    },

    handleNodeClick(data) {
      console.log(data);
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        console.log("获取数据成功", data.data);
        this.menus = data.data;
      });
    },
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    edit(data) {
      this.title = "修改分类";
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        console.log("edit -> data", data);
        this.category = data.category;
      });
    },
    editCategory() {
      console.log("editCategory -> ", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "分类修改成功!"
        });
        this.dialogVisible = false;
        // 刷新菜单
        this.getMenus();
        // 默认展开菜单
        this.expandedKey = [this.category.parentCid];
        this.category = [];
      });
    },
    append(data) {
      this.title = "添加分类";
      this.dialogType = "add";
      this.dialogVisible = true;
      console.log("append -> ", data);
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
    },
    addCategory() {
      console.log("addCategory -> ", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "分类添加成功!"
        });
        this.dialogVisible = false;
        // 刷新菜单
        this.getMenus();
        // 默认展开菜单
        this.expandedKey = [this.category.parentCid];
      });
    },
    remove(node, data) {
      this.pCid.push(node.parent.data.parentCid);
      this.categoryDelete([data.catId], data.name);
    },
    categoryDelete(ids, name) {
      this.$confirm(`是否删除【${name}】菜单`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "菜单删除成功!"
            });
            // 刷新菜单
            this.getMenus();
            // 默认展开菜单
            this.expandedKey = this.pCid;
            this.$refs.tree.setCheckedKeys([]);
          });
        })
        .catch(() => {});
    }
  },
  //生命周期，创建加载
  created() {
    this.getMenus();
  }
};
</script>

<style>
</style>